/*******************************************************************************
 * Copyright (c) 2006 CEA List.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     CEA List - initial API and implementation
 *******************************************************************************/
package com.cea.papyrus.core.commands;

import java.util.List;

import org.eclipse.gef.commands.Command;
import org.eclipse.uml2.uml.Element;

/**
 * Command that moves an element in a {@link List}.
 * 
 * @author Remi SCHNEKENBURGER
 */
public class MoveInListCommand extends Command {
	
	/**
	 * old index of the element in the list.
	 */
	protected int oldIndex;
	
	/**
	 * new index of the element in the list.
	 */
	protected int newIndex;
	
	/**
	 * element to move.
	 */
	protected Element element;
	
	/**
	 * list to modify.
	 */
	protected List list;
	
	/**
	 * Default constructor.
	 * 
	 * @param element the element to move in the given list
	 * @param list the list to be changed
	 * @param newIndex the new index of the element in the given list
	 */
	public MoveInListCommand(List list, Element element, int newIndex) {
		this.list = list;
		this.element = element;
		this.newIndex = newIndex;
		if(oldIndex==-1) {
			throw new RuntimeException(element+ " is not in the list "+list);
		}
	}
	
	/* (non-Javadoc)
	 * @see org.eclipse.gef.commands.Command#execute()
	 */
	/**
	 * 
	 */
	@Override
	public void execute() {
		this.oldIndex = list.indexOf(element);
		list.remove(oldIndex);
		list.add(newIndex, element);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.gef.commands.Command#redo()
	 */
	/**
	 * 
	 */
	@Override
	public void redo() {
		execute();
	}
	
	/* (non-Javadoc)
	 * @see org.eclipse.gef.commands.Command#undo()
	 */
	/**
	 * 
	 */
	@Override
	public void undo() {
		list.remove(newIndex);
		list.add(oldIndex, element);
	}
}
